<template>
  <div>
    <el-badge
      :hidden="isMsg"
      :value="msgNum"
      :max="10"
      class="badge-item"
      @click.native="alarmRecord()"
    >
      <i class="iconfont iconbellring" style="font-size: 24px" />
    </el-badge>
    <audio ref="sound" class="sound" src="../../../public/static/audio/1.mp3" />
  </div>
</template>

<script>
import bus from '@/utils/bus'
import socketService from '../../utils/wbsocket/ws'
import { mapGetters } from 'vuex'

import { getUnprocessedNum } from '@/api/cy'
import { getToken } from '@/utils/auth'
import { baseUrl } from '@/utils/global.js'
// import dayjs from 'dayjs'
const dayjs = require('dayjs')
export default {

  data() {
    return {
      isMsg: true, // 是否显示消息数量
      msgNum: 0, // 消息数量
      order: 0,
      heartBeatInterval: null,
      waitTimeLock: false,
      waitTimeInterval: null,
      waitTime: 0, // 等待时间(s)
      internalHandle: null,

      collapse: false,
      fullscreen: false,
      name: 'CSL',
      message: 0,
      websock: null, // websocket连接对象
      notifyIndex: 0, // 通知的索引
      notifyArray: [], // 存放通知
      activeIndex: '0',
      items: [], // 总菜单数据
      contents: [], // 目录数据
      subItems: [],
      strTitle: '位置业务融合管理平台',
      logoPath: '',
      headPicPath: '',
      valueLang: '',
      alarmOption: [
        { type: 'SOS', label: 'SOS告警' },
        { type: 'alarmIn', label: '非法进入' },
        { type: 'gatherOver', label: '超员告警' },
        { type: 'alarmOut', label: '非法离开' },
        { type: 'lackOfStaff', label: '缺员告警' },
        { type: 'stay', label: '滞留告警' },
        { type: 'freeFal', label: '跌倒告警' },
        { type: 'temporary', label: '一键撤离成功' },
        { type: 'lowBattery', label: '低电量告警' },
        { type: 'disappear', label: '消失告警' }
      ]
    }
  },
  computed: {
    ...mapGetters({
      wsData: 'wsData/GET_BELLMSG'
    })
  },
  watch: {
    wsData(value, oldValue) {
      // console.log('监听websocket数据变化', value, oldValue)
      if (value) {
        this.receiveWs(value)
      }
    }
  },
  mounted() {
    this.getUnproNum()
    this.internalHandle = setInterval(() => {
      this.getUnproNum()
    }, 1000 * 20)
    this.initWS()
  },
  beforeDestroy() {
    bus.$off('sosflash')
    bus.$off('removenewfence')
    bus.$off('alarmInfo')
  },
  destroyed() {
    socketService.close()
    if (this.internalHandle != null) {
      clearInterval(this.internalHandle)
    }
  },

  methods: {
    alarmTypeAll(value) {
      var title
      for (let i = 0; i < this.alarmOption.length; i++) {
        if (this.alarmOption[i].type == value) {
          title = this.alarmOption[i].label
        }
      }
      return title || '未知名告警'
    },
    shenyi(item) {
      console.log(item)
      const autos = this.$refs.sound
      autos.src = require('../../../public/static/audio/4.mp3')
      autos.play()
    },
    getUnproNum() {
      getUnprocessedNum('all').then(res => {
        const RES = this.responseUse(res)
        let NUM = 0
        for (let i = 0; i < RES.length; i++) {
          NUM = NUM + RES[i].num
        }
        this.msgNum = NUM
        if (this.msgNum > 0) {
          this.isMsg = false
        }
      })
    },

    // 跳转消息提示框
    alarmRecord() {
      this.$router.push({ path: '/security/alarmRecord' })
      // this.$router.push({ path: '/changchun/alarmStrategy' })
    },
    initWS() {
      if (socketService.socket == null) {
        socketService.init()
        setTimeout(() => {
          socketService.send('程序已上线，开始接收告警')
          this.sendTime()
        }, 3000)
      } else if (socketService.getState() != 1) {
        socketService.init()
      }
    },

    sendTime() {
      console.log(this.heartBeatInterval)
      if (this.heartBeatInterval == null) {
        this.sendWsInfo()
      }
      this.heartBeatInterval = setInterval(() => {
        if (socketService.getState() != 1) {
          clearInterval(this.heartBeatInterval)
          socketService.init()
          setTimeout(() => {
            socketService.send('程序已上线，开始接收告警')
            this.sendTime()
          }, 3000)

          return
        }
        this.sendWsInfo()
      }, 6000)
    },

    closewb: function(e) {
      console.log('socket已经关闭', e)
    },

    // closeweb() {
    //   socketService.socket.close()
    // },
    // openweb() {
    //   if (socketService.socket == null) {
    //     socketService.init()
    //     setTimeout(() => {
    //       socketService.send('程序已上线，开始接收告警')
    //       this.sendTime()
    //     }, 3000)
    //   } else if (socketService.getState() != 1) {
    //     socketService.init()
    //   }
    // },

    // 接受websocket消息处理
    receiveWs(wsObj) {
      const self = this
      const jsonData = JSON.parse(wsObj.data)
      if (jsonData.message === 'handshake') {
        socketService.send('alarm:token:' + getToken())
      } else if (jsonData.message === 'HeartBeat') {
        // 监听是否此链接是否断开
        self.waitTime = 0
        // console.log("接收到后端返回信息，waitTime清零");
        self.waitTimeLock = false
      } else if (jsonData.message === 'alarm') {
        // 判断当前显示的是否是大屏展示模块
        if (self.$route.path !== '/dashboard') {
          let bRet = false
          for (let i = 0; i < jsonData.data.length; i++) {
            // 判断是否为SOS，如果是，通知对告警对象添加振波特效
            if (
              self.$store.state.wsData.sosFlashLock &&
              jsonData.data[i].alarmType === 'SOS'
            ) {
              bus.$emit('sosflash', jsonData.data[i])
            }

            let detailInfo = jsonData.data[i].resourceName
            const detailArray = []
            const alarmType = jsonData.data[i].alarmType
            detailArray[0] = jsonData.data[i].resourceName
            // detailArray[1] = jsonData.data[i].intime
            detailArray[1] = dayjs(jsonData.data[i].intime).format('YYYY-MM-DD HH:mm:ss')
            detailArray[3] = jsonData.data[i].fenceName

            if (alarmType === 'alarmIn') {
              // 非法进入
              detailArray[2] = self.$t('alarm.alarmTypes.illegalEntry')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else if (alarmType === 'alarmOut') {
              // 非法离开
              detailArray[2] = self.$t('alarm.alarmTypes.illegalDeparture')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else if (alarmType === 'gatherOver') {
              // 超员告警
              detailArray[2] = self.$t('alarm.alarmTypes.overAlert')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else if (alarmType === 'lackOfStaff') {
              // 缺员告警
              detailArray[2] = self.$t('alarm.alarmTypes.missingAlarm')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else if (alarmType === 'stay') {
              // 滞留告警
              detailArray[2] = self.$t('alarm.alarmTypes.retentionAlarm')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else if (alarmType === 'freeFal') {
              // 跌倒告警

              detailArray[2] = self.$t('alarm.alarmTypes.fallWarning')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else if (alarmType === 'temporary') {
              // 一键撤离成功

              detailArray[0] = jsonData.data[i].layerName
              detailArray[1] = jsonData.data[i].remark
              detailArray[2] = this.formatDate(jsonData.data[i].intime)
              // detailArray[3] = jsonData.data[i].status;
              let ss = ''
              if (jsonData.data[i].status == '0') {
                ss = self.$t('alarm.alarmTypes.process')
              } else if (jsonData.data[i].status == '1') {
                ss = self.$t('alarm.alarmTypes.success')
              } else {
                ss = self.$t('alarm.alarmTypes.fail')
              }
              detailArray[3] = ss
              detailInfo = self.$t(
                'alarm.evacuationAlertNotification',
                detailArray
              )
            } else if (alarmType === 'SOS') {
              detailArray[2] = self.$t('alarm.alarmTypes.sosAlarm')
              detailInfo = self.$t('alarm.sosAlarmInformation', detailArray)
            } else if (alarmType === 'lowBattery') {
              detailArray[2] = self.$t('alarm.alarmTypes.lowBattery')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)

              // 低电量弹窗
            } else if (alarmType === 'disappear') {
              // 消失告警
              detailArray[2] = self.$t('alarm.alarmTypes.disappear')
              detailInfo = self.$t('alarm.alarmInformation', detailArray)
            } else {
              detailInfo = jsonData.data[i].detail
            }

            // 将组合过的信息添加到当前数据中，防止在下面无法进行匹配
            jsonData.data[i]['detailInfo'] = detailInfo

            bRet = false
            for (let j = 0; j < self.notifyArray.length; j++) {
              if (
                jsonData.data[i].detailInfo &&
                self.notifyArray[j].title === jsonData.data[i].detailInfo
              ) {
                bRet = true
                break
              }
            }
            if (!bRet) {
              setTimeout(
                function(
                  title,
                  message,
                  type,
                  layerid,
                  showaudio,
                  audiofilepath
                ) {
                  // 判断是否是关闭围栏的响应消息
                  if (type === 'temporary') {
                    bus.$emit('removenewfence', layerid)
                  }
                  self.openWarningFrame(title, message)
                  self.notifyIndex++
                  // self.message++

                  // 播放告警音频
                  self.playAlarmVoice(type, showaudio, audiofilepath)
                },
                100,
                // jsonData.data[i].event,
                jsonData.data[i].alarmType,
                detailInfo,
                jsonData.data[i].alarmType,
                jsonData.data[i].layerId,
                jsonData.data[i].showAudio,
                jsonData.data[i].audioFilePath
              )
            }
          }
        } else {
          // 当前显示为大屏模块
          // 不在弹出通知窗口
          // 将信息传递到Dashboard模块
          bus.$emit('alarmInfo', jsonData.data)
        }
      }
    },

    pushWsData() {

    },

    // 播放告警信息
    playAlarmVoice(alarmtype, showaudio, audiofilepath) {
      if (alarmtype === 'SOS') {
        // 播放本地音频文件
        // $('.voiceplay').attr('src', '../../../public/static/audio/2.mp3')
        this.shenyi('../../../public/static/audio/1.mp3')
      } else {
        // 判断是否开启音频文件
        // 如果开启，播放服务器上的音频文件
        if (showaudio === 1) {
          if (audiofilepath != null) {
            // $('.voiceplay').attr('src', 'http://192.168.3.33' + '/' + audiofilepath)
            const audioUrl = `http://${baseUrl}\${audiofilepath}`
            // this.shenyi(audioUrl)
            const autos = this.$refs.sound
            autos.src = require(audioUrl)
            autos.play()
          } else {
            this.shenyi()
          }
        } else {
          this.shenyi()
        }
      }
    },

    /**
     * 打开告警弹框
     */
    // openWarningFrame(title, message) {
    //   console.log(title)
    //   const self = this
    //   if (self.notifyArray.length >= 5) {
    //     // 去除第一个
    //     const temp = self.notifyArray.shift()
    //     temp.close()
    //   }

    //   const obj = self.$notify({
    //     title: self.alarmTypeAll(title),
    //     dangerouslyUseHTMLString: true,
    //     message: `<div>${message}</div>
    //     <div style="text-align:right">
    //     <span style="padding:6px 10px;margin:12px;background:#1890ff;color:#fff;cursor:pointer">
    //     查看</span></div>`,
    //     // message: message,
    //     type: 'warning', // 弹框的种类success/warning/info/error
    //     duration: 0, // 显示时间，0表示不自动关闭
    //     position: 'bottom-right',
    //     offset: 0,
    //     // onClick() {
    //     //   self.defineCallBack(message) // 自定义回调,message为传的参数
    //     // },
    //     onClose: self.notifyClick,
    //     customClass: 'alarm_notify'
    //   })

    //   self.notifyArray.push(obj)
    // },
    openWarningFrame(title, message) {
      const self = this
      if (self.notifyArray.length >= 5) {
        // 去除第一个
        const temp = self.notifyArray.shift()
        temp.close()
      }
      const h = self.$createElement
      const obj = self.$notify({
        dangerouslyUseHTMLString: true, // 是否将message属性作为HTML片段处理
        title: '(' + self.alarmTypeAll(title) + ')' + message,
        message: h(
          'button',
          {
            on: {
              click: self.notifyClick
            },
            style: {
              float: 'right',
              fontSize: '12px',
              color: '#fff',
              backgroundColor: '#1890ff',
              border: 'none',
              // width: "70px",
              padding: '5px 10px 5px 10px',
              borderRadius: '3px'
            }
          },
          self.$t('header.detail')
        ),
        // message: message,
        type: 'warning', // 弹框的种类success/warning/info/error
        duration: 0, // 显示时间，0表示不自动关闭
        position: 'bottom-right',
        offset: 0,
        onClose: self.notifyClose,
        customClass: 'alarm_notify'
      })

      self.notifyArray.push(obj)
    },

    notifyClose(obj) {
      for (let i = 0; i < this.notifyArray.length; i++) {
        if (obj.id === this.notifyArray[i].id) {
          this.notifyArray.splice(i, 1)
          break
        }
      }
    },

    notifyClick() {
      // 1、跳转到告警列表里去
      this.$router.push({ path: '/security/alarmRecord' })
      // 2、同时删除所有通知框
      const len = this.notifyArray.length
      let temp
      for (let i = 0; i < len; i++) {
        temp = this.notifyArray.shift()
        temp.close()
      }

      this.message = 0
    },

    sendWsInfo() {
      this.order++
      socketService.send(
        'HeartBeat:{order:' +
          this.order +
          ',timeStamp:' +
          new Date().getTime() +
          '}'
      )
      this.waitTimeLock = true
      this.waitTime = 0
    },

    initNum() {
      this.msgNum = 10
    }
  }
}
</script>

<style scoped>
/deep/ .el-badge__content.is-fixed {
  top: 15px;
  right: 18px;
}
</style>
